package com.xbongbong.workflow.service.strategy.data.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.domain.entity.PaasUserEntity;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.FlowStatusEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.enums.TaskTypeEnum;
import com.xbongbong.paas.model.PaasUserModel;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.util.FormDataUtil;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.formdata.pojo.SaasNeedRedundantAttrPojo;
import com.xbongbong.pro.workflow.enums.WorkflowOperateEnum;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.model.PaasFormDataModel;
import com.xbongbong.saas.model.PaasFormSubDataModel;
import com.xbongbong.workflow.domain.entity.WorkflowBackupDataEntity;
import com.xbongbong.workflow.model.WorkflowBackupDataModel;
import com.xbongbong.workflow.pojo.Data;
import com.xbongbong.workflow.pojo.WorkflowTransferPOJO;
import com.xbongbong.workflow.service.help.saas.WorkFlowSaasStageHelp;
import com.xbongbong.workflow.service.strategy.data.AbstractWorkflowDataStrategy;
import com.xbongbong.workflow.service.strategy.data.WorkflowDataProcessStrategy;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 *
 * @author 魏荣杰
 *
 */
@Service
@Slf4j
public class WorkflowPaasDataStrategy extends AbstractWorkflowDataStrategy implements WorkflowDataProcessStrategy {

    private static final Logger LOGGER = LoggerFactory.getLogger(WorkflowPaasDataStrategy.class);

    @Resource
    private WorkflowBackupDataModel workflowBackupDataModel;
    @Resource
    private PaasFormDataModel paasFormDataModel;
    @Resource
    private PaasFormSubDataModel paasFormSubDataModel;
    @Resource
    private PaasUserModel paasUserModel;
    @Resource
    private WorkFlowSaasStageHelp workFlowSaasStageHelp;

    @Override
    public List<Integer> type() {
        return Collections.singletonList(XbbRefTypeEnum.PAAS.getCode());
    }

    @Override
    public void save(WorkflowTransferPOJO workflowTransferPOJO, SaasNeedRedundantAttrPojo saasNeedRedundantAttrPojo) throws XbbException {
        // 文件柜
        saveDataCabinetFile(workflowTransferPOJO);
        //阶段处理
        workFlowSaasStageHelp.afterSaveStage(workflowTransferPOJO);
        // api
        apiHook(workflowTransferPOJO);
        addLinkDataDynamic(workflowTransferPOJO);
        // log
        afterSaveLog(workflowTransferPOJO);
    }

    @Override
    public void update(WorkflowTransferPOJO workflowTransferPOJO, SaasNeedRedundantAttrPojo saasNeedRedundantAttrPojo) throws XbbException {
        // 文件柜
        saveDataCabinetFile(workflowTransferPOJO);
        //阶段处理
        workFlowSaasStageHelp.afterSaveStage(workflowTransferPOJO);
        // api
        apiHook(workflowTransferPOJO);
        // log
        afterUpdateLog(workflowTransferPOJO);
    }

    @Override
    public void updateBack(Long taskId, WorkflowTransferPOJO workflowTransferPOJO) throws XbbException {
        try {
            String corpid = workflowTransferPOJO.getCorpid();
            Long backupDataId = workflowTransferPOJO.getBackupDataId();
            Long dataId = workflowTransferPOJO.getData().getId();
            WorkflowBackupDataEntity workflowBackupDataEntity = workflowBackupDataModel.getByKey(backupDataId, corpid);
            if (Objects.nonNull(workflowBackupDataEntity)) {
                JSONObject data = workflowBackupDataEntity.getData();

                replenishAttrForBackupData(workflowTransferPOJO.getData().getData(), data);

                PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
                paasFormDataEntity.setId(dataId);
                paasFormDataEntity.setCorpid(corpid);
                paasFormDataEntity.setData(data);
                paasFormDataEntity.setSerialNo(data.getString(FieldTypeEnum.SERIALNO.getAlias()));
                paasFormDataEntity.setOwnerId(getOwnerId(data));
                paasFormDataEntity.setDepartmentId(data.getLong(FieldTypeEnum.DEPARTMENTID.getAlias()));
                List<PaasUserEntity> paasUserList = JSON.parseArray(data.getString(StringConstant.USER_TEAM), PaasUserEntity.class);
                FormDataUtil.removeSystemData(data);
                data.remove(StringConstant.USER_TEAM);
                if (Objects.equals(workflowTransferPOJO.getOperate(), WorkflowOperateEnum.UPDATE.getType())) {
                    paasFormDataEntity.setFlowStatus(FlowStatusEnum.PASS.getType());
                }
                paasFormDataModel.update(paasFormDataEntity);

                // 回退被删掉的子表单
                updateBackSubForm(paasFormDataEntity, corpid, IndexTypeEnum.IDX_SUB_FORM_DATA);
                //回退被删掉的富文本
                updateBackRichText(taskId, workflowTransferPOJO);
                saveUserTeam(paasUserList, corpid, paasFormDataEntity.getId());
            }
        } catch (Exception e) {
            LOGGER.error("WorkflowPaasDataStrategy.updateBack.error ", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }

    private void saveUserTeam(List<PaasUserEntity> list, String corpid, Long dataId) throws XbbException {
        try {
            List<PaasUserEntity> paasUserList = paasUserModel.getPaasUserList(corpid, dataId, null);
            List<Long> idList = new ArrayList<>();
            list.forEach(item->idList.add(item.getId()));
            paasUserList.removeIf(item->idList.contains(item.getId()));
            if (CollectionsUtil.isNotEmpty(paasUserList)) {
                paasUserModel.deleteBatch(corpid, paasUserList, DelEnum.DELETE.getDel());
            }
            if (CollectionsUtil.isNotEmpty(list)) {
                paasUserModel.updateBatch(list);
            }
        } catch (Exception e) {
            log.error("com.xbongbong.workflow.service.strategy.data.impl.WorkflowClueStrategy.saveUserTeam error ", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }

    @Override
    public void approvalFailed(Long taskId, WorkflowTransferPOJO workflowTransferPOJO, Integer taskType) throws XbbException {
        try {
            String corpid = workflowTransferPOJO.getCorpid();
            Data workflowData = workflowTransferPOJO.getData();
            Long dataId = workflowData.getId();
            Long formId = workflowData.getFormId();
            Integer businessType = workflowData.getBusinessType();
            Integer saasMark = workflowData.getSaasMark();
            PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
            paasFormDataEntity.setId(dataId);
            if (Objects.equals(TaskTypeEnum.REVOKE.getType(), taskType)) {
                paasFormDataEntity.setFlowStatus(FlowStatusEnum.REVOKE.getType());
            } else {
                paasFormDataEntity.setFlowStatus(FlowStatusEnum.REJECT.getType());
            }
            paasFormDataEntity.setCorpid(corpid);
            paasFormDataEntity.setUpdateTime(DateTimeUtil.getInt());
            paasFormDataModel.update(paasFormDataEntity);
            // 子表单
            DelEnum del = DelEnum.APPROVE_FAILED;

            paasFormSubDataModel.deleteBatchByDataId(Collections.singletonList(dataId), corpid, IndexTypeEnum.IDX_SUB_FORM_DATA, del);

            //富文本
            deleteFormRichText(dataId, corpid, formId, businessType, saasMark, DelEnum.NORMAL);

            // 团队
            List<PaasUserEntity> paasUserList = paasUserModel.getPaasUserList(corpid, dataId, null);
            if (CollectionsUtil.isNotEmpty(paasUserList)) {
                paasUserModel.deleteBatch(corpid, paasUserList, del.getDel());
            }

        } catch (Exception e) {
            LOGGER.error("WorkflowPaasDataStrategy.approvalFailed.error ", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }
}
